<template>
  <div>
    <div class="app_card mb-2 pt-4  pb-4">
      <div class="d-flex justify-content-between search-form">
        <div class="flex-grow-1">
          <!-- <el-radio-group class="radio_button mr-5" v-model="radioFloor" @change="floorChange">
            <el-radio-button label="-1">全部</el-radio-button>
            <el-radio-button label="-2">上课教室</el-radio-button>
            <el-radio-button label="-3">故障教室</el-radio-button>
          </el-radio-group> -->
          <el-select clearable class="w200px mr-3" v-model="queryForm.buildingId" placeholder="请选择大楼" autocomplete="off">
            <el-option v-for="item in buildingStore.bildingList" :key="item.id" :label="item.name"
              :value="item.id"></el-option>
          </el-select>
          <el-button type="primary" plain @click="onRefresh()">查询</el-button>
          <el-button type="info" @click="onReset()" link>重置</el-button>

        </div>
        <div class="d-flex">
          <el-button type="primary" @click="onAdd()">新增设备 </el-button>
          <el-button type="primary" plain @click="onSearch()">导入</el-button>
          <el-button type="primary" plain @click="onSearch()">导出</el-button>
        </div>
      </div>
    </div>
    <div class="app_card pt-4  pb-5">
      <el-table v-loading="loading" element-loading-text="查询中..." stripe size="large" :data="dataOfTable"
        height="calc(100vh - 300px)">
        <el-table-column label="设备ID" prop="id" align="center" minWidth="100">
          <template #default="scope">{{ scope.row.id }}</template>
        </el-table-column>
        <el-table-column label="大楼" prop="building" align="center" show-overflow-tooltip minWidth="100">
          <template #default="scope">{{ scope.row.building }}</template>
        </el-table-column>
        <el-table-column label="楼层" prop="floor" align="center" show-overflow-tooltip minWidth="100">
          <template #default="scope">{{ scope.row.floor }}</template>
        </el-table-column>
        <el-table-column label="教室" prop="room" align="center">
          <template #default="scope">{{ scope.row.room }}</template>
        </el-table-column>
        <el-table-column label="设备名称" prop="name" align="center" show-overflow-tooltip minWidth="100">
          <template #default="scope">{{ scope.row.name }}</template>
        </el-table-column>
        <el-table-column label="设备品牌" prop="brand" align="center" show-overflow-tooltip minWidth="100">
          <template #default="scope">{{ scope.row.brand }}</template>
        </el-table-column>
        <el-table-column label="设备型号" prop="model" align="center" show-overflow-tooltip minWidth="100">
          <template #default="scope">{{ scope.row.model }}</template>
        </el-table-column>
        <el-table-column label="序号" prop="group" align="center" show-overflow-tooltip minWidth="100">
          <template #default="scope">
            {{ findValue(grouOption, scope.row.group) }}
          </template>
        </el-table-column>
        <el-table-column label="购买时间" prop="purchasingDate" align="center" show-overflow-tooltip minWidth="100">
          <template #default="scope">
            {{ scope.row.purchasingDate.split(" ")[0] }}
          </template>
        </el-table-column>
        <el-table-column label="寿命周期" prop="serviceLife" align="center" show-overflow-tooltip minWidth="100">
          <template #default="scope">{{ scope.row.serviceLife }}</template>
        </el-table-column>
        <el-table-column label="使用时长" prop="purchasingDate" width="180" align="center">
          <template #default="scope">
            <el-progress :stroke-width="18" :percentage="fontDatas(scope.row.purchasingDate)"></el-progress>
          </template>
        </el-table-column>
        <el-table-column label="设备类型" prop="type" align="center" show-overflow-tooltip minWidth="100">
          <template #default="scope">
            <template v-if="scope.row.type">
              {{ findValue(typeOption, scope.row.type) }}</template>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="160" align="center">
          <template #default="scope">
            <el-button link type="primary" @click="onEditRow(scope.row)">编辑</el-button>
            <el-button link type="primary" @click="onDeleteRow(scope.row)">删除</el-button>
            <el-button link type="primary" @click="goClassroomDetail(scope.row)">跳转</el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination ref="paginationRef" @handleChange="handleChange" />
    </div>
    <EditDialog ref="editDialogRef" @success="loadData()"></EditDialog>
  </div>
</template>

<script setup>
/**
 * 资产管理
 */
import { useRouter, useRoute } from "vue-router";
import { ref, onMounted } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import EsAjax from '@/utils/EsAjax';
import ApiUrls from '@/apis/index';
import { typeList, groupList } from '@/apis/model/EquipmentModel';
import { findValue } from '@/utils/EsCommon';
import useBuildingStore from '@/stores/useBuildingStore';
const buildingStore = useBuildingStore();

//组件
import Pagination from '@/components/pagination/index.vue';
import EditDialog from './EditDialog.vue';
// ======================================================
//                      变量声明
// ======================================================
const loading = ref(false);

const router = useRouter();
// 组件引用
const paginationRef = ref(null);
const editDialogRef = ref(null);

const typeOption = ref(typeList);
const grouOption = ref(groupList);
// 表格数据
const dataOfTable = ref([]);
// 表格查询参数
const queryForm = ref({
  buildingId: ""
})
// 表格查询参数
const queryParam = ref({
  sort: "id",
  order: "desc",
  page: 1,
  limit: 10,
  query: ""
})

const radioFloor = ref('-1');

// 
// ======================================================
//                      处理事件
// ======================================================

const floorChange = () => {
  if (radioFloor.value == "-2") {//上课
  } else if (radioFloor.value == "-3") {//故障教室
  } else if (radioFloor.value == "-1") {//全部
  } else {

  }
}
const fontDatas = (row) => {
  //console.log(row)
  var nowTime = row;
  var thisTime = nowTime;
  thisTime = thisTime.replace(/-/g, "/");
  var time = new Date(thisTime);
  time = time.getTime();
  console.log('time===', time)

  if (!isNaN(time)) {
    var time_stamp = Date.parse(new Date());
    let num = parseInt(
      ((time_stamp - time) / 1000 / 60 / 60 / 24 / 30 / 36) * 100
    );
    if (num < 0) num = 0
    return num
  } else {
    return 0
  }
}
const onReset = () => {
  queryForm.value.buildingId = ""
  onRefresh()
}
// 点击刷新按钮
const onRefresh = () => {
  queryParam.value.page = 1;
  paginationRef.value?.changeTotal({ totalCount: 0 })
  loadData();
}


// 点击新增按钮
const onAdd = (row = null) => {
  if (row) {
    editDialogRef.value.show(0, "新增" + row.title, row);
    return;
  }
  editDialogRef.value.show(0, "新增");
}


// 点击快速搜索按钮
const onSearch = (param) => {
  loadData();
}

// 点击行内编辑按钮
const onEditRow = (row) => {
  editDialogRef.value.show(row.id, "编辑", row);
}

// 点击行内删除按钮
const onDeleteRow = (row) => {
  ElMessageBox.confirm("确定要删除该记录吗？", "警告").then(() => {
    EsAjax.post(ApiUrls.equipmentDelete, { ids: String(row.id) })
      .then(res => {
        if (res.data.code != 200) {
          ElMessage.warning(res.data.data + res.data.msg);
          return;
        }
        ElMessage.success('删除成功');

        loadData();
      })
      .catch(err => { ElMessage.error("网络错误：", err.message) });
  }).catch(() => { });
  console.log(row)
}
// 点击跳转
const goClassroomDetail = (row) => {
  localStorage.setItem("ROOM_DATA", JSON.stringify(row));

  router.push({
    path: '/classroom/detail', query: { id: row.id }
  })
}

// 处理分页尺寸
const handleChange = (data = null) => {
  queryParam.value.page = data?.page;
  queryParam.value.limit = data?.limit;
  loadData();
}
// ======================================================
//                      处理事件
// ======================================================

const loadData = () => {
  let _queryParam = queryParam.value
  _queryParam.query = ''
  if (queryForm.value.buildingId) {
    _queryParam.query = "buildingId=" + queryForm.value.buildingId;
  }
  _queryParam.offset = (_queryParam.page - 1) * _queryParam.limit || 0;
  loading.value = true
  EsAjax.post(ApiUrls.equipmentDatagrid, { ..._queryParam }).then(res => {
    if (res.data.code != 200) {
      ElMessage.warning(res.data.data + res.data.msg);
      return;
    }
    let { list, totalCount } = res.data.data
    dataOfTable.value = list;
    paginationRef.value?.changeTotal({ totalCount: totalCount })
  }).catch(err => {
    ElMessage.error(err.message);
  }).finally(() => {
    loading.value = false
  })
}


onMounted(() => {
  loadData();
  buildingStore.getBuildList()

})

</script>
<style lang="less" scoped>
:deep(.el-progress-bar__inner) {
  background-color: #ffbb00;
}
</style>
  
